//
//  ClubDynamicSearchListViewController.swift
//  77Club
//
//  Created by Apple on 2025/1/9.
//

import UIKit
import ZLPhotoBrowser
import JXSegmentedView

class ClubDynamicSearchListViewController: ClubBaseViewController, RaeAnimationProtocol {

    private let searchTextF = c_make_ex(UITextField.self)
        .corner(15).bgColor("#7B7D80".toColor.alpha(0.08))
        .color("#2E3033").font(12.font_medium)
        .placeholder("请输入关键进行搜索").end()
    private let cancelButton = c_make_ex(UIButton.self)
        .text("取消").color("#47494D").font(15.font_semiBold).end()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubDynamicListCell.self,ClubSquareForumEmptyCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 306.0.Scale
        tableView.estimatedSectionHeaderHeight = 0
        tableView.sectionFooterHeight = 0
        tableView.contentInset = UIEdgeInsets.zero
        tableView.sectionHeaderTopPadding = 0
        return tableView
    }()
    
    private var currentVC = true
    private var playingIndexPath: IndexPath?
    private var isSearch = false
    private var sourceData = [ClubGameCircleModel](){
        didSet{
            self.tableView.reloadData()
            self.loadFirstVideo()
        }
    }
    var updateHistoryData: (() -> Void)?
    var keyword: String = "" {
        didSet{
            loadData()
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        currentVC = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        currentVC = false
        NotificationCenter.default.post(name: .stopDynamicAudioPlayer, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if isSearch {
            self.updateHistoryData?()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            searchTextF
            cancelButton
            tableView
        }
        
        searchTextF.leading(12.0.Scale).top(.statusHeight + 8.0.Scale).width(295.0.Scale).height(30)
        cancelButton.trailing(0).height(30)
        cancelButton.CenterY == searchTextF.CenterY
        cancelButton.Leading == searchTextF.Trailing
        tableView.trailing(0).leading(0).bottom(.safe_bottom)
        tableView.Top == searchTextF.Bottom + 5.0.Scale
        
        searchTextF.style { v in
            v.placehold("#AEB0B3".toColor, font: 12.font_medium)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 26, height: 30))
            let searchImg = UIImageView(frame: CGRect(x: 6, y: 7, width: 16, height: 16))
            searchImg.image = "Home_searchGray".toImage
            leftV.addSubview(searchImg)
            v.leftView = leftV
            v.leftViewMode = .always
            v.returnKeyType = .search
            v.delegate = self
        }
        
        cancelButton.addTarget(self, action: #selector(clickDismissButton), for: .touchUpInside)
        NotificationCenter.default.addObserver(self, selector: #selector(updateNewData), name: .updateDynamicListData, object: nil)
    }

    @objc private func clickDismissButton(){
        self.navigationController?.popViewController(animated: true)
    }

    @objc private func updateNewData(){
        loadData()
    }
    
    private func loadData(){
        
        self.sourceData.removeAll()
        Task{
            ToastUtil.show()
            let res = await network.requestSpecialData(.searchDynamic(keyword: keyword), type: ClubGameCircleModel.self)
            ToastUtil.dismiss()
            if res.isSuccess, let models = res.models {
                var arr = [ClubGameCircleModel]()
                if models.count > 0 {
                    for md in models {
                        var mod = md
                        var itemSize: CGSize = .zero
                        if md.video.count > 0 {
                            itemSize = .zero
                        }else if md.img.count == 1 {
                            itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                        }else if md.img.count == 2 {
                            itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                        }else if md.img.count > 2 {
                            let w = (CGFloat.screenWidth - 110.0.Scale)/3
                            itemSize = CGSize (width: w, height: w)
                        }else{
                            itemSize = .zero
                        }
                        mod.itemSize = itemSize
                        arr.append(mod)
                    }
                }
                self.sourceData = arr
            }
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubDynamicSearchListViewController: UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if sourceData.count == 0 {
            return 1
        }
        return sourceData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if sourceData.count == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ClubSquareForumEmptyCell", for: indexPath) as! ClubSquareForumEmptyCell
            cell.titleString = "空空如也~"
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicListCell", for: indexPath) as! ClubDynamicListCell
        cell.circleModel = self.sourceData[indexPath.row]
        cell.jumpToDetail = { id in
            let detailController = ClubDynamicDetailViewController()
            detailController.dynamicID = id
            self.navigationController?.pushViewController(detailController, animated: true)
        }
        cell.didSelectImage = { index,images in
            self.selectImage(index: index, images: images)
        }
        cell.didSelectVideo = { url in
            self.selectVideo(url: url)
        }
        cell.toGameDetailVC = { gid in
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = gid
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.toTopicDetailVC = { topicId in
            let detailVC = ClubTopicDetailViewController()
            detailVC.topicId = topicId
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.showMoreView = { md in
            let moreView = ClubMoreView()
            moreView.uid_des = md.uid_des
            moreView.reportBlock = {
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    let reportVC = ClubReportViewController()
                    reportVC.dynamicID = md.id
                    reportVC.updateDataBlock = {
                        self.loadData()
                    }
                    self.present(reportVC, animated: true)
                }else{
                    self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                }
            }
            moreView.delBlock = {
                Task{
                    let res = await self.network.request(.delDynamic(id: md.id))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.loadData()
                    }
                }
            }
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type, shareUrl: md.share_url)
            }
            self.entryAnimate.animation(show: moreView)
        }
        cell.otherUserInfoVC = { uid in
            if uid.count > 0 {
                if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                    let otherVC = ClubMineInfoViewController()
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }else{
                    let otherVC = ClubOtherInfoViewController()
                    otherVC.uid = uid
                    otherVC.updateBlock = {
                        self.loadData()
                    }
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }
            }            
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailController = ClubDynamicDetailViewController()
        detailController.dynamicID = sourceData[indexPath.row].id
        detailController.updateDataBlock = {
            self.loadData()
        }
        self.navigationController?.pushViewController(detailController, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let visibleCells = tableView.visibleCells as? [ClubDynamicListCell] else { return }
            
        // 获取 TableView 的中心位置
        let tableViewCenter = tableView.bounds.size.height / 2 + tableView.contentOffset.y

        for cell in visibleCells {
            guard let indexPath = tableView.indexPath(for: cell) else { continue }
            let cellCenterY = cell.center.y

            // 判断 Cell 中心是否接近 TableView 中心
            if tableView.contentOffset.y == 0 {
                loadFirstVideo()
            }
            if abs(cellCenterY - tableViewCenter) < 100 { // 设定 50 为接近程度的阈值
                if playingIndexPath != indexPath {
                    playingIndexPath = indexPath
                    cell.playVideo()  // 播放视频
                }
            } else {
                if playingIndexPath == indexPath {
                    cell.pauseVideo()  // 暂停视频
                    playingIndexPath = nil
                }
            }
        }
    }

    // 监听 return 键（即搜索按钮）被点击
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        // 隐藏键盘
        textField.resignFirstResponder()
        // 执行搜索操作
        searchAction(text: textField.text)
        return true
    }
    
    // 搜索操作的逻辑
    func searchAction(text: String?) {
        if let searchText = text, !searchText.isEmpty {
            
            self.isSearch = true
            searchTextF.text = ""
            self.keyword = searchText
            if var history = UserDefaultsManager.getString(forKey: .squareSearchHistory), history.count > 0 {
                history.append("," + searchText)
                UserDefaultsManager.setString(history, forKey: .squareSearchHistory)
            }else{
                var tempArray = [String]()
                tempArray.append(searchText)
                let wordArray = tempArray.joined(separator: ",")
                UserDefaultsManager.setString(wordArray, forKey: .squareSearchHistory)
            }
        }
    }
}

//MARK: action
extension ClubDynamicSearchListViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func shareDetail(type: Int, shareUrl: String) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.dynamicShareTitle, description: ClubGlobalTool.shared.dynamicShareDes, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: shareUrl)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.dynamicShareTitle, des: ClubGlobalTool.shared.dynamicShareDes, image: "AppIcon".toImage!, shareUrl: shareUrl, shareType: type)
        }
    }
    
    private func loadFirstVideo(){
        
        if currentVC && self.sourceData.count > 0 {
            let md = self.sourceData[0]
            if md.video.count > 0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    let indexPath = IndexPath(row: 0, section: 0)
                    self.playingIndexPath = indexPath
                    let cell = self.tableView.cellForRow(at: indexPath) as! ClubDynamicListCell
                    cell.playVideo()  // 播放视频
                }
            }
        }
    }
}
